<?php
// 检查是否已安装
if (file_exists(__DIR__ . '/system/sql.php')) {
    header("Location: index.php");
    exit;
}

// 处理表单提交
$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $db_host = $_POST['db_host'] ?? 'localhost';
    $db_user = $_POST['db_user'] ?? '';
    $db_pass = $_POST['db_pass'] ?? '';
    $db_name = $_POST['db_name'] ?? '';
    $db_port = $_POST['db_port'] ?? '3306';

    // 测试数据库连接
    try {
        $link = @mysqli_connect($db_host, $db_user, $db_pass, '', $db_port);
        if (!$link) {
            throw new Exception(mysqli_connect_error());
        }

        // 创建数据库（如果不存在）
        if (!mysqli_select_db($link, $db_name)) {
            if (!mysqli_query($link, "CREATE DATABASE IF NOT EXISTS `{$db_name}` CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci")) {
                throw new Exception("创建数据库失败: " . mysqli_error($link));
            }
            mysqli_select_db($link, $db_name);
        }

        // 创建数据表
        $sql = <<<EOD
SET NAMES utf8;
SET time_zone = '+00:00';
SET foreign_key_checks = 0;
SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO';

SET NAMES utf8mb4;

DROP TABLE IF EXISTS `admin_log`;
CREATE TABLE `admin_log` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '日志操作序列',
  `uid` int(11) NOT NULL COMMENT '日志操作用户',
  `ip` varchar(20) NOT NULL COMMENT '日志操作IP',
  `text` text NOT NULL COMMENT '日志操作内容',
  `time` int(11) NOT NULL COMMENT '日志操作时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;


DROP TABLE IF EXISTS `admin_user`;
CREATE TABLE `admin_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '管理员序列',
  `username` varchar(255) NOT NULL COMMENT '管理员用户名',
  `password` varchar(255) NOT NULL COMMENT '管理员密码',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

INSERT INTO `admin_user` (`id`, `username`, `password`) VALUES
(1,	'admin',	'21232f297a57a5a743894a0e4a801fc3');

DROP TABLE IF EXISTS `article_article`;
CREATE TABLE `article_article` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '文章序列',
  `wbtreeid` int(11) NOT NULL COMMENT '所属栏目序列',
  `title` varchar(255) NOT NULL COMMENT '文章标题',
  `author` varchar(255) NOT NULL COMMENT '文章作者',
  `url` varchar(255) NOT NULL COMMENT '文章外链',
  `content` text NOT NULL COMMENT '文章内容',
  `time` int(11) NOT NULL COMMENT '发表时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;


DROP TABLE IF EXISTS `article_menu`;
CREATE TABLE `article_menu` (
  `wbtreeid` int(11) NOT NULL AUTO_INCREMENT COMMENT '菜单栏目序列',
  `menu` varchar(255) NOT NULL COMMENT '菜单栏目',
  `status` int(11) NOT NULL COMMENT '是否在首页显示',
  `nav` int(11) NOT NULL COMMENT '是否在导航显示',
  PRIMARY KEY (`wbtreeid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;


DROP TABLE IF EXISTS `webinfo`;
CREATE TABLE `webinfo` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '网站信息序列',
  `webname` varchar(255) NOT NULL COMMENT '网站名称',
  `keyword` text NOT NULL COMMENT '网站关键词',
  `description` text NOT NULL COMMENT '网站描述',
  `logo` varchar(255) NOT NULL COMMENT '网站LOGO',
  `icp` varchar(255) NOT NULL COMMENT 'ICP备案',
  `icpwa` varchar(255) NOT NULL COMMENT '网安备案',
  `wacode` varchar(255) NOT NULL COMMENT '网安备案数字代码',
  `address` text NOT NULL COMMENT '联系地址',
  `connect` text NOT NULL COMMENT '联系电话',
  `email` varchar(255) NOT NULL COMMENT '联系邮箱',
  `static` int(11) NOT NULL COMMENT '网站伪静态',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;


DROP TABLE IF EXISTS `web_banners`;
CREATE TABLE `web_banners` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '轮播图序列',
  `title` varchar(100) NOT NULL COMMENT '轮播图标题',
  `slogan` varchar(200) NOT NULL COMMENT '轮播图简介',
  `url` varchar(255) NOT NULL COMMENT '轮播图地址',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
EOD;

        // 执行SQL语句
        if (mysqli_multi_query($link, $sql)) {
            do {
                if ($result = mysqli_store_result($link)) {
                    mysqli_free_result($result);
                }
            } while (mysqli_next_result($link));
        } else {
            throw new Exception("创建数据表失败: " . mysqli_error($link));
        }

        // 生成配置文件
        $configContent = <<<EOD
<?php
\$link = mysqli_connect('{$db_host}', '{$db_user}', '{$db_pass}', '{$db_name}', '{$db_port}');
\$system = "绿贝文章内容管理系统";
\$article = "article_article";
EOD;

        if (!is_dir(__DIR__ . '/system')) {
            mkdir(__DIR__ . '/system', 0755, true);
        }

        if (file_put_contents(__DIR__ . '/system/sql.php', $configContent)) {
            header("Location: index.php");
            exit;
        } else {
            $error = '配置文件写入失败，请检查目录权限';
        }
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>系统安装向导</title>
    <link href="/static/bootstrap.min.css" rel="stylesheet">
</head>

<body class="bg-light">
    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-md-6">
                <div class="card shadow-sm">
                    <div class="card-header bg-primary text-white">
                        <h4 class="mb-0">绿贝文章内容管理系统</h4>
                    </div>
                    <div class="card-body">
                        <?php if ($error): ?>
                            <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
                        <?php endif; ?>
                        <form method="post">
                            <div class="mb-3">
                                <label for="db_host" class="form-label">数据库地址</label>
                                <input type="text" class="form-control" id="db_host" name="db_host" value="localhost" required>
                            </div>
                            <div class="mb-3">
                                <label for="db_port" class="form-label">端口</label>
                                <input type="number" class="form-control" id="db_port" name="db_port" value="3306" required>
                            </div>
                            <div class="mb-3">
                                <label for="db_user" class="form-label">用户名</label>
                                <input type="text" class="form-control" id="db_user" name="db_user" required>
                            </div>
                            <div class="mb-3">
                                <label for="db_pass" class="form-label">密码</label>
                                <input type="password" class="form-control" id="db_pass" name="db_pass">
                            </div>
                            <div class="mb-3">
                                <label for="db_name" class="form-label">数据库名</label>
                                <input type="text" class="form-control" id="db_name" name="db_name" required>
                            </div>
                            <button type="submit" class="btn btn-primary w-100">安装系统</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script src="/static/bootstrap.bundle.min.js"></script>
</body>

</html>